import xml2js from "xml2js";
import template from "./tpl";
import qs from "querystring";
import sha1 from "sha1";
// 解析 xml
export const parmsXml = xml => {
  return new Promise((resolve, reject) => {
    xml2js.parseString(xml, { trim: true }, (err, content) => {
      if (err) {
        reject(err);
      } else {
        resolve(content);
      }
    });
  });
};

// 解析数据为 json
export const formatMessage = result => {
  let message = {};

  if (typeof result === "object") {
    const keys = Object.keys(result);

    for (let i = 0; i < keys.length; i++) {
      let item = result[keys[i]];
      let key = keys[i];

      if (!(item instanceof Array) || item.length === 0) {
        continue;
      }

      if (item.length === 1) {
        let val = item[0];

        if (typeof val === "object") {
          message[key] = formatMessage(val);
        } else {
          message[key] = (val || "").trim();
        }
      } else {
        message[key] = [];

        for (let j = 0; j < item.length; j++) {
          message[key].push(formatMessage(item[j]));
        }
      }
    }
  }

  return message;
};

// 模板配置 并输出 回复xml
export const tpl = (content, message) => {
  let type = "text";

  if (Array.isArray(content)) {
    type = "news";
  }

  if (!content) {
    content = "Empty News";
  }

  if (content && content.type) {
    type = content.type;
  }

  let info = Object.assign(
    {},
    {
      content: content,
      createTime: new Date().getTime(),
      msgType: type,
      toUserName: message.FromUserName,
      fromUserName: message.ToUserName
    }
  );
  return template(info);
};

// 签名算法
export const sign = (ticket, url) => {
  const noncestr = String(Math.random(30)).substr(2,10);
  const timestamp = Date.now() * 1000;
  let form = {
    jsapi_ticket: ticket,
    noncestr,
    timestamp,
    url
  };
  const reqUrl = qs.stringify(form);
  const signature = sha1(reqUrl);
  return {
    noncestr,
    timestamp,
    signature
  }
};
